<template>
	<view>
		<view class="wrap-container">
			<!-- <view class="warp-input" v-for="(item,index) in inputData"> -->
			<view class="warp-input">
				<view class="warp-text">设备名称:</view>
				<u-input v-model="equipment_name" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">设备编号:</view>
				<u-input v-model="equip_id" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">设备型号:</view>
				<u-input v-model="equipment_typecode" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">安装日期:</view>
				<u-input v-model="usetime" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">安装位置:</view>
				<u-input v-model="useplace" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">设备坐标:</view>
				<u-input v-model="coordinate" :type="type" :border="border" :height="height" :disabled="true" />
				<u-button @click="navMap(coordinate,equipment_name)" style="margin-left: 24rpx;"
					type="primary">查看</u-button>
			</view>
			<view class="warp-input">
				<view class="warp-text">电耗:</view>
				<u-input v-model="energy_waste" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">状态:</view>
				<u-input v-model="status" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
			<view class="warp-input">
				<view class="warp-text">网络状态:</view>
				<u-input v-model="network_status" :type="type" :border="border" :height="height" :disabled="true" />
			</view>
		</view>

		<view class="charts-box">
			<l-echart style="width:100%;" ref="chartRef" @finished="init()"></l-echart>
		</view>

	</view>
</template>
<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
	export default {
		data() {
			return {
				option: {
					xAxis: {
						type: 'category',
						data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
					},
					title: {
						text: '实时数据',
						textStyle: {
							color: '#333',
							fontSize: 12
						},
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'cross',
							label: {
								backgroundColor: '#6a7985'
							}
						},
						
						position: function (point, params, dom, rect, size) {
						  // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
						  // 提示框位置
						  var x = 0; // x坐标位置
						  var y = 0; // y坐标位置
						 
						  // 当前鼠标位置
						  var pointX = point[0];
						  var pointY = point[1];
						 
						  // 外层div大小
						  // var viewWidth = size.viewSize[0];
						  // var viewHeight = size.viewSize[1];
						 
						  // 提示框大小
						  var boxWidth = size.contentSize[0];
						  var boxHeight = size.contentSize[1];
						 
						  // boxWidth > pointX 说明鼠标左边放不下提示框
						  if (boxWidth > pointX) {
						    x = 5;
						  } else { // 左边放的下
						    x = pointX - boxWidth;
						  }
						 
						  // boxHeight > pointY 说明鼠标上边放不下提示框
						  if (boxHeight > pointY) {
						    y = 5;
						  } else { // 上边放得下
						    y = pointY - boxHeight;
						  }
						 
						  return [x, y];
						}
					},
					legend: {
						data: ['Email'],
						right: 0,
						textStyle: {
							color: '#333',
							fontSize: 8
						},
					},
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						top: '28%',
						containLabel: true
					},
					yAxis: {
						type: 'value'
					},
					series: [{
						name: 'Email',
						type: 'line',
						stack: 'Total',
						areaStyle: {},
						emphasis: {
							focus: 'series'
						},
						data: [120, 132, 101, 134, 90, 230, 210]
					}]
				},
				id: "",
				type: 'text',
				height: 60,
				border: true,
				equipment_name: "",
				equip_id: "",
				equipment_typecode: "",
				usetime: "",
				useplace: "",
				status: "",
				energy_waste: "",
				network_status: "",
				coordinate: "",
				ntervalId: null, // 定时器的 ID
				refreshCount: 0, // 计数器，记录当前已经请求的次数
				tags: [],
				count: 5,
				chart: '',
				valuesList: []
			}
		},

		onLoad(e) {
			this.startRefreshing();
			this.id = e.id
		},
		onReady() {
			this.getEqView();
		},
		onHide() {
			this.stopRefreshing();
			console.log('组件销毁')
		},
		beforeDestroy() {
			this.stopRefreshing(); // 在组件销毁前停止定时刷新
			console.log('组件销毁')
		},
		onUnload() {
			this.stopRefreshing();
			console.log('组件销毁')
		},
		methods: {
			async init() {
				// chart 图表实例不能存在data里
				this.chart = await this.$refs.chartRef.init(echarts);
				this.chart.setOption(this.option)
			},
			refreshData() {
				this.$u.api.monitor({
					algorithmProcessId: "getEqReal",
					param: {
						data: {
							structure_uuid: this.equip_id
						}
					}
				}).then(response => {
					this.tags = response.data.data.result.tags;
					this.updateChartData();
				}).catch(error => {
					console.error('数据获取错误:', error);
					alert('数据刷新失败，请稍后再试。');
				});
			},
			valuesByIndex(id) {
				return this[`values${id}`] || (this[`values${id}`] = []);
			},
			timesByIndex(id) {
				return this[`timesList${id}`] || (this[`timesList${id}`] = []);
			},
			updateChartData() {
				if (!this.tags.length) return;

				// 获取每个 tag 的数据，并更新 valuesList 和 timesList
				this.tags.forEach(tag => {
					const valuesList = this.valuesByIndex(tag.id);
					const timesList = this.timesByIndex(tag.id);
					const values = tag.value;
					const time = tag.times.substring(11, 19);
					valuesList.push(values);
					timesList.push(time);

					if (valuesList.length > 5) {
						valuesList.shift();
						timesList.shift();
					}
				});

				// 提取图例数据
				const legendData = [...new Set(this.tags.map(tag => tag.tagDescribe))];

				// 初始化系列数据
				const seriesData = legendData.map(describe => {
					const id = this.tags.find(tag => tag.tagDescribe === describe).id;
					const valuesList = this.valuesByIndex(id);
					const timesList = this.timesByIndex(id);

					return {
						name: describe,
						type: 'line',
						data: valuesList.map((value, index) => ({
							value: value,
							name: timesList[index]
						}))
					};
				});

				// 更新图表配置
				this.option.xAxis.data = this.valuesByIndex(this.tags[0].id).map((_, index) => this.timesByIndex(this.tags[
					0].id)[index]);
				this.option.legend.data = legendData;
				this.option.series = seriesData;

				// 确保图表实例存在
				if (this.chart) {
					this.chart.setOption(this.option);
				}

			},

			getEqView() {
				this.$u.api.eqView({
					"algorithmProcessId": "getEqview",
					"param": {
						"data": {
							id: this.id
						}
					}
				}).then(Response => {
					const res = Response.data.data.result[0]
					this.equipment_name = res.equipment_name
					this.equip_id = res.equip_id
					this.refreshData();

					this.equipment_typecode = res.equipment_typecode
					this.usetime = res.usetime
					let coordinateArr = res.coordinate.split(",").map(item => item.trim());
					this.coordinate = (coordinateArr[0] && coordinateArr[1]) ?
						`${coordinateArr[0]},${coordinateArr[1]}` : '';

					this.useplace = res.useplace
					if (res.status) {
						let statusMap = {
							'1': '异常',
							'2': '运行',
							'3': '停止',
							'4': '维修维护'
						};
						this.status = statusMap[res.status]
					}
					if (res.network_status) {
						let netMap = {
							'1': '运行',
							'0': '在线',
						};
						this.network_status = netMap[res.network_status]
					}
				})
			},

			startRefreshing() {
				const interval = 5000; // 1秒等于1000毫秒

				// 设置定时器，每隔1秒执行一次refreshData方法
				this.intervalId = setInterval(() => {
					this.refreshData();
					console.log('轮询开始')
				}, interval);
			},
			stopRefreshing() {
				clearInterval(this.intervalId); // 停止定时器
			},

			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			navMap(coordinate, equipment_name) {
				uni.navigateTo({
					url: "/pages/sys/workbench/install?coordinate=" + coordinate + "&equipment_name=" +
						equipment_name
				});

			},
		}
	}
</script>
<style lang="scss">
	@import 'index.scss';

	page {
		background-color: #f5f5f5;
		width: 100%;
		padding: 24rpx;
	}

	.wrap-container {
		width: 100%;
		height: 880rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-top: 12rpx;
		margin-bottom: 48rpx;


		.warp-input {
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			margin: 24rpx 0;

			.warp-text {
				width: 24%;
				text-align: right;
				padding-right: 24rpx;
			}
		}
	}


	.charts-box {
		width: 100%;
		height: 540rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 48rpx;
	}
</style>